import tkinter as tk
from tkinter import Canvas
from pynput import mouse
import threading
import numpy as np
from PIL import ImageGrab
from playsound import playsound
import time

class ScreenMonitor:
    def __init__(self):
        # 初始化参数
        self.monitor_area = None
        self.drawing = False
        self.threshold = 5000  # 像素波动阈值
        self.running = True

        # 创建透明窗口用于框选
        self.root = tk.Tk()
        self.root.attributes('-alpha', 0.3)
        self.root.overrideredirect(True)
        self.root.attributes('-topmost', True)
        self.canvas = Canvas(self.root, bg='gray', highlightthickness=0)
        self.canvas.pack(fill=tk.BOTH, expand=True)
        self.rect_id = None

        # 启动鼠标监听线程
        self.mouse_listener = mouse.Listener(on_click=self.on_click, on_move=self.on_move)
        self.mouse_listener.start()

        # 启动主循环
        self.root.mainloop()

    def on_click(self, x, y, button, pressed):
        if button == mouse.Button.left:
            if pressed:
                # 开始框选
                self.start_x, self.start_y = x, y
                self.drawing = True
                self.root.geometry(f'1x1+{x}+{y}')
                self.root.deiconify()
            else:
                # 结束框选，启动监控线程
                self.drawing = False
                self.root.withdraw()
                self.end_x, self.end_y = x, y
                left = min(self.start_x, self.end_x)
                top = min(self.start_y, self.end_y)
                width = abs(self.end_x - self.start_x)
                height = abs(self.end_y - self.start_y)
                self.monitor_area = (left, top, left + width, top + height)
                print(f"监控区域已设定：{self.monitor_area}")
                threading.Thread(target=self.monitor_fluctuation).start()

    def on_move(self, x, y):
        # 动态绘制框选矩形
        if self.drawing:
            left = min(self.start_x, x)
            top = min(self.start_y, y)
            width = abs(x - self.start_x)
            height = abs(y - self.start_y)
            self.root.geometry(f'{width}x{height}+{left}+{top}')
            if self.rect_id:
                self.canvas.delete(self.rect_id)
            self.rect_id = self.canvas.create_rectangle(0, 0, width, height, outline='red', width=2)

    def monitor_fluctuation(self):
        # 屏幕波动检测
        last_frame = None
        while self.running and self.monitor_area:
            current_frame = np.array(ImageGrab.grab(bbox=self.monitor_area))
            if last_frame is not None:
                diff = np.sum(np.abs(current_frame - last_frame))
                if diff > self.threshold:
                    print(f"检测到波动！差异值：{diff}")
                    self.play_alert()
            last_frame = current_frame
            time.sleep(0.5)

    def play_alert(self):
        # 播放警报音效
        try:
            playsound('alert.mp3')
        except Exception as e:
            print(f"音频播放失败：{e}")

    def stop(self):
        # 安全退出
        self.running = False
        self.root.destroy()

if __name__ == "__main__":
    monitor = ScreenMonitor()